package vip.learning.order.rpc.service.impl;


import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.learning.order.rpc.entity.OrderDO;
import vip.learning.order.rpc.feign.AccountFeignClient;
import vip.learning.order.rpc.feign.WareFeignClient;
import vip.learning.order.rpc.mapper.OrderMapper;
import vip.learning.order.rpc.rest.vo.OrderVo;
import vip.learning.order.rpc.service.OrderService;

import java.util.Random;


/**
 * @ClassName OrderService
 * @Description
 * @Author hubin
 * @Date 2021/1/27 17:40
 * @Version V1.0
 **/
@Service
public class OrderServiceImpl implements OrderService {


    @Autowired
    private OrderMapper orderMapper;


    @Autowired
    private AccountFeignClient accountFeignClient;

    @Autowired
    private WareFeignClient wareFeignClient;


    @Override
 //   @SentinelResource("backend")
    public void backendServer() {
        System.out.println("service .......");
    }

    @Override
    @GlobalTransactional
    @Transactional(rollbackFor = Exception.class)
    public OrderVo createOrder(String userId, String commodityCode, Integer count) {

        OrderDO orderDO = new OrderDO();
        orderDO.setUserId(userId);
        orderDO.setCommodityCode(commodityCode);
        orderDO.setCount(count);
        int next = new Random().nextInt(10);
        // id
        orderDO.setMoney(next);
        orderDO.setId(next);

        // 创建订单
        orderMapper.insert(orderDO);

        // 扣减库存
        wareFeignClient.dedubt(commodityCode,count);
        // 扣减账户
        accountFeignClient.debit(userId,count);

        OrderVo orderVo = new OrderVo();

        BeanUtils.copyProperties(orderDO,orderVo);

        return orderVo;
    }
}

